package com.le.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.le.edu.domain.entity.Chapter;
import com.le.edu.domain.entity.Section;
import com.le.edu.domain.vo.ChapterInfoVO;
import com.le.edu.domain.vo.SectionVO;
import com.le.edu.mapper.ChapterMapper;
import com.le.edu.service.ChapterService;
import com.le.edu.service.SectionService;
import com.le.edu.service.VideoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 17447
 * @description 针对表【t_chapter(课程)】的数据库操作Service实现
 * @createDate 2024-04-09 10:57:34
 */
@Service
@RequiredArgsConstructor
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter>
        implements ChapterService {
    private final SectionService sectionService;
    private final VideoService videoService;

    @Override
    public List<ChapterInfoVO> getChapterAndSectionVoList(Long courseId) {
        List<ChapterInfoVO> chapterInfoVOS = baseMapper.selectChapterVo(courseId);
        List<SectionVO> sectionVOS = sectionService.selectSectionVo(courseId);
        // 封装章节和对应的课时
        List<ChapterInfoVO> voList = chapterInfoVOS.stream()
                .peek(chapterInfoVO -> {
                    Long chapterId = chapterInfoVO.getChapterId();

                    List<SectionVO> sectionVOList = sectionVOS.stream()
                            .filter(sectionVo -> chapterId.equals(sectionVo.getChapterId()))
                            .toList();
                    chapterInfoVO.setSections(sectionVOList);
                })
                .toList();
        return voList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delChapterAndSectionAndVideoByChapterId(Long chapterId) {
        //删除章节
        baseMapper.deleteById(chapterId);
        // 待删除章节下的所有课时
        List<Section> sectionList = sectionService.list(new LambdaQueryWrapper<Section>()
                .eq(Section::getChapterId, chapterId));
        // 收集要删除的课时id
        List<Long> sectionIds = sectionList.stream()
                .map(Section::getSectionId)
                .toList();
        // 删除课时
        sectionService.removeByIds(sectionIds);
        // 收集要删除的视频id
        List<Long> videoIds = sectionList.stream()
                .map(Section::getVideoId)
                .distinct()
                .filter(videoId -> {
                    long count = sectionService.count(new LambdaQueryWrapper<Section>()
                            .eq(Section::getVideoId, videoId)
                            .notIn(Section::getSectionId, sectionIds));
                    // 过滤没有被使用的视频id
                    return count == 0;
                }).toList();
        //视频表删除 and minio删除视频
        videoService.removeTableAndVodByIds(videoIds);
    }
}




